package com.nf.health.app.http;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.nf.health.app.MyApplication;
import com.nf.health.app.core.HttpActionHandle;
import com.nf.health.app.utils.PreferenceHelper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HttpStringRequest {
	private String Tag = HttpStringRequest.class.getSimpleName();
	private static HttpStringRequest httpStringRequest;
	private static final int TIMEOUT_MS = 50 * 1000;

	private HttpStringRequest() {
	}
	public static HttpStringRequest getInstance() {
		if (httpStringRequest == null) {
			synchronized (HttpStringRequest.class) {
				if (httpStringRequest == null) {
					httpStringRequest = new HttpStringRequest();
				}
			}
		}
		return httpStringRequest;
	}
	/**
	 *
	 * @param actionHandle
	 * @param method
	 * @param url
	 * @param getParam
	 * @param postParam
	 * @param header
	 * @param listener
	 * @param errorListener
	 * @return
	 */
	public StringRequest request(HttpActionHandle actionHandle, final int method, String url,final Map<String, String> getParam,final Map<String, String> postParam,final Map<String, String> header, Listener<String> listener,ErrorListener errorListener) {
		final String back_url = url;
		try {
			if (getParam != null) {
				StringBuilder params = new StringBuilder();
				params.append("?");
				Set<Map.Entry<String, String>> set = getParam.entrySet();
				for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
						.hasNext();) {
					Map.Entry<String, String> entry = it
							.next();
					params.append(entry.getKey() + "");
					params.append("=");
					params.append(URLEncoder.encode(entry.getValue() + "",
							"UTF-8"));
					params.append("&");
				}
				if (params.length() > 0) {
					url += params.substring(0, params.length() - 1);
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringRequest stringRequest = new StringRequest(method, url, listener,
				errorListener) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				return postParam;
			}
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				return header == null ? super.getHeaders() : header;
			}
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				Map<String, String> responseHeaders = response.headers;
				String cookies = responseHeaders.get("Set-Cookie");
				
				if(back_url.contains(Apis.HOST_COMMON) && cookies != null){
					String[] cookiesArr = cookies.split(";");
					for(int i=0; i< cookiesArr.length; i++){
						if(cookiesArr[i].contains("NF_USER_SESSION")){
							String NF_USER_SESSION = cookiesArr[i].replace("NF_USER_SESSION=","");
							PreferenceHelper.putString(PreferenceHelper.NF_USER_SESSION,NF_USER_SESSION);
						}
					}
				}
				String dataString;
				try {
					dataString = new String(response.data, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					return super.parseNetworkResponse(response);
				}
				return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
			}

		};
		stringRequest.setTag(actionHandle.hashCode());
		stringRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_MS,
				DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		MyApplication.getRequestQueue().add(stringRequest);
		return stringRequest;

	}

	/**
	 *
	 * @param actionHandle
	 * @param method
	 * @param url
	 * @param param
	 * @param headerMap
	 * @param listener
	 * @param errorListener
	 * @return
	 */
	public StringRequest request(HttpActionHandle actionHandle, final int method, String url,final Map<String, String> param,
			final Map<String, String> headerMap, Listener<String> listener,ErrorListener errorListener) {
		final String back_url = url;
		try {
			if (method == Method.GET && param != null) {
				StringBuilder sb = new StringBuilder();
				sb.append("?");
				Set<Map.Entry<String, String>> set = param.entrySet();
				for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext();) {
					Map.Entry<String, String> entry = it.next();
					sb.append(entry.getKey() + "");
					sb.append("=");
					sb.append(URLEncoder.encode(entry.getValue() + "","UTF-8"));
					sb.append("&");
				}
				if (sb.length() > 0) {
					url += sb.substring(0, sb.length() - 1);
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringRequest stringRequest = new StringRequest(method, url, listener, errorListener) {

			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				return param == null ? super.getParams() : param;
			}

			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {

				Map<String, String> header = null;
				if (headerMap != null) {
					header = new HashMap<String, String>();
					Set<String> keys = headerMap.keySet();

					StringBuffer sb = new StringBuffer();
					for (String key : keys) {
						sb.append(key);
						sb.append("=");
						sb.append(headerMap.get(key));
						sb.append(";");
					}
					String cookies = sb.toString();
					cookies = cookies.substring(0, cookies.length() - 1);
					header.put("Cookie", cookies);
				}
				return header == null ? super.getHeaders() : header;
			}

			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				Map<String, String> responseHeaders = response.headers;
				String cookies = responseHeaders.get("Set-Cookie");
				
				if(back_url.contains(Apis.HOST_COMMON) && cookies != null){
					String[] cookiesArr = cookies.split(";");
					for(int i=0; i< cookiesArr.length; i++){
						if(cookiesArr[i].contains("NF_USER_SESSION")){
							String NF_USER_SESSION = cookiesArr[i].replace("NF_USER_SESSION=","");
							PreferenceHelper.putString(PreferenceHelper.NF_USER_SESSION,NF_USER_SESSION);
						}
					}
				}
				String dataString;
				try {
					dataString = new String(response.data, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					return super.parseNetworkResponse(response);
				}
				return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
			}
		};
		stringRequest.setTag(actionHandle.hashCode());
		stringRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_MS,
				DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		MyApplication.getRequestQueue().add(stringRequest);
		return stringRequest;
	}
}
